package com.ag.oa.util;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import java.util.List;
import java.util.Map;

/**
 * Created by yxm on 14/10/2021.
 * 网络请求工具类
 */
public class NetClientUtil {

    private static final Logger logger = LoggerFactory.getLogger(NetClientUtil.class);

    /**
     * 向指定URL发送GET方法的请求
     * @param url: 发送请求的URL
     * @return 请求结果
     */
    @SuppressWarnings("unused")
    public static String sendGet(String url) {

        StringBuilder result = new StringBuilder();
        BufferedReader in = null;

        try {
            // 打开和URL之间的连接
            URL realUrl = new URL(url);
            URLConnection connection = realUrl.openConnection();

            // 设置通用的请求属性
            connection.setRequestProperty("accept", "*/*");
            connection.setRequestProperty("connection", "Keep-Alive");
            connection.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
            connection.connect();   // 建立实际的连接

            // 获取所有响应头字段
            Map<String, List<String>> map = connection.getHeaderFields();
            for (String key: map.keySet()) {

            }

            // 定义 BufferedReader输入流来读取URL的响应
            in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
            String line;
            while ((line = in.readLine()) != null) {
                result.append(line);
            }
        }catch (Exception e) {
            logger.error("--get 请求异常: "+ e);
        }finally {
            // 使用finally块来关闭输入流
            try {
                if (in!=null) {
                    in.close();
                }
            }catch (Exception e2) {
                logger.error("--get 请求异常: "+ e2);
            }
        }
        return result.toString();
    }

    /**
     * 发送POST方法的请求
     * @param url: 发送请求的 URL
     * @param params: 请求参数。
     * @return 响应结果
     */
    public static String sendPost(String url, Map<String, String> params) {

        PrintWriter out = null;
        BufferedReader in = null;
        StringBuilder result = new StringBuilder();

        try {
            // 打开和URL之间的连接
            URL realUrl = new URL(url);
            //HttpsURLConnection conn = (HttpsURLConnection) realUrl.openConnection();
            URLConnection conn = realUrl.openConnection();

            // 设置通用的请求属性
            conn.setRequestProperty("accept", "*/*");
            conn.setRequestProperty("connection", "Keep-Alive");
            conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");

            // 发送POST请求必须设置如下两行
            conn.setDoOutput(true);
            conn.setDoInput(true);

            out = new PrintWriter(conn.getOutputStream());  // 获取连接, URLConnection对象对应的输出流
            out.print(getUrlParamsFromMap(params));         // 发送请求参数
            out.flush();  // flush输出流的缓冲

            // 定义BufferedReader输入流来读取URL的响应
            in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
            String line;
            while ((line = in.readLine()) != null) {
                result.append(line);
            }
        }catch (Exception e) {
            e.printStackTrace();  // 连接异常
        }finally {
            ioClose(out, in); // 关闭输出流、输入流
        }
        return result.toString();
    }

    /**
     * description: 将 map 转换成 url 参数格式: name1=value1&name2=value2
     */
    private static String getUrlParamsFromMap(Map<String, String> map) {
        try {
            if (null != map) {
                StringBuilder stringBuilder = new StringBuilder();
                for (Map.Entry<String, String> entry : map.entrySet()) {
                    stringBuilder.append(URLEncoder.encode(entry.getKey(), "UTF-8")).append("=")
                            .append(URLEncoder.encode(entry.getValue(), "UTF-8")).append("&");
                }
                String content = stringBuilder.toString();
                if (content.endsWith("&")) {
                    content = StringUtils.substringBeforeLast(content, "&");
                }
                return content;
            }
        } catch (Exception e) {
            logger.error("--getUrlParamsFromMap 方法异常: "+ e);
        }
        return null;
    }

    private static void ioClose(PrintWriter out, BufferedReader in) {
        try {
            if (out!=null) {
                out.close();
            }
            if (in!=null) {
                in.close();
            }
        }catch (IOException ex) {
            logger.error("--IO关闭异常: "+ ex);
        }
    }

}
